package com.thh.shirodemo.config;

import com.thh.shirodemo.bean.User;
import com.thh.shirodemo.mapper.UserMapper;
import com.thh.shirodemo.service.UserService;
import org.apache.log4j.lf5.LF5Appender;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shkstart
 * @create 2022-07-20-22:29
 */
@Configuration
public class UserIdRealm extends AuthenticatingRealm {
   @Resource
   private UserService userService;
   @Resource
   private UserMapper userMapper;

   private Logger logger= LoggerFactory.getLogger(UserIdRealm.class);
    //实现认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("UserIdRealm的认证方法");
        //获取当前用户
        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
        String username=userToken.getUsername();

        //获得数据库中的用户来和当前用户进行比对，认证
        User user = userService.queryUserById(Integer.parseInt(username));
        //如果没有查到用户 表示没有该用户
        if(user==null){
            return null;
            //后面会抛出UnknownAccountException异常
        }
        List<String> roles = userMapper.getRoles(user.getUserRoles());
        user.setUserPerms(roles);

        //加入我们需要的添加的盐用来加密
        ByteSource salt = ByteSource.Util.bytes("saltAdrian");
        //返回AuthenticationToken,完成认证流程

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getUserPass(),salt,"myRealm");
        //shiro帮我们进行密码认证(密码敏感 已经包装好了)
        return simpleAuthenticationInfo;
    }
}
